﻿using Coldairarrow.Business.PB;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.PB;
using Coldairarrow.Entity.Print;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Coldairarrow.Util.ClassLibrary;
using Coldairarrow.Util.Helper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Coldairarrow.Api.Controllers.PB
{
    [Route("/PB/[controller]/[action]")]
    public class PB_Material_TempController : BaseApiController
    {
        #region DI
        private readonly RedisOptions _redisOptions; //1.声明实体
        private readonly MongoDBOptions _mongodbOptions;
        public PB_Material_TempController(IPB_Material_TempBusiness pB_Material_TempBus, IPB_MaterialTypeBusiness pB_MaterialTypeBus, IOptions<MongoDBOptions> mongodbOptions, IOptions<RedisOptions> redisOptions, IOperator op, IServiceProvider provider)
        {
            _pB_Material_TempBus = pB_Material_TempBus;
            _provider = provider;
            _Op = op;
            _redisOptions = redisOptions.Value;//3.赋值
            _mongodbOptions = mongodbOptions.Value;
        }
        IPB_MaterialTypeBusiness _pB_MaterialTypeBus { get; }
        IPB_Material_TempBusiness _pB_Material_TempBus { get; }
        IOperator _Op { get; }
        IServiceProvider _provider { get; }
        #endregion

        #region 获取

        [HttpPost]
        public async Task<PageResult<PB_Material_Temp>> GetDataList(PageInput<ConditionDTO> input)
        {
            return await _pB_Material_TempBus.GetDataListAsync(input);
        }
        [HttpPost]
        public async Task<PageResult<PB_Material_TempDTO>> QueryDataList(PageInput<PBMateria_TemplConditionDTO> input)
        {
            return await _pB_Material_TempBus.QueryDataListAsync(input);
        }
        [HttpPost]
        public async Task<PB_Material_Temp> GetTheData(IdInputDTO input)
        {
            return await _pB_Material_TempBus.GetTheDataAsync(input.id);
        }

        #endregion

        #region 提交

        [HttpPost]
        public async Task SaveData(PB_Material_Temp data)
        {
            if (data.Id.IsNullOrEmpty())
            {
                InitEntity(data);

                await _pB_Material_TempBus.AddDataAsync(data);
            }
            else
            {
                await _pB_Material_TempBus.UpdateDataAsync(data);
            }
        }

        [HttpPost]
        public async Task DeleteData(List<string> ids)
        {
            await _pB_Material_TempBus.DeleteDataAsync(ids);
        }

        /// <summary>
        /// 物料数据导入
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        public AjaxResult Import(IFormFile file)// file
        {
            string ReturnValue = string.Empty;
            //定义一个bool类型的变量用来做验证
            bool flag = true;
            try
            {
                #region 检查文件
                string fileExt = Path.GetExtension(file.FileName).ToLower();
                //定义一个集合一会儿将数据存储进来,全部一次丢到数据库中保存
                var Data = new List<PB_Material_Temp>();
                var liststr = new List<string>();
                MemoryStream ms = new MemoryStream();
                file.CopyTo(ms);
                ms.Seek(0, SeekOrigin.Begin);
                IWorkbook book;
                if (fileExt == ".xlsx")
                {
                    book = new XSSFWorkbook(ms);
                }
                else if (fileExt == ".xls")
                {
                    book = new HSSFWorkbook(ms);
                }
                else
                {
                    book = null;
                }
                ISheet sheet = book.GetSheetAt(0);

                int CountRow = sheet.LastRowNum + 1;//获取总行数

                if (CountRow - 1 == 0)
                {
                    return Error("Excel列表数据项为空!");

                }
                #endregion
                #region 循环验证
                for (int i = 1; i < CountRow; i++)
                {
                    //获取第i行的数据
                    var row = sheet.GetRow(i);
                    if (row != null)
                    {
                        //循环的验证单元格中的数据
                        for (int j = 0; j < sheet.LastRowNum; j++)
                        {  
                            if (j == 3)
                            {
                                if (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0)
                                {
                                    flag = false;
                                    return Error(ReturnValue += $"第{i + 1}行,第{j + 1}列数据不能为空。");
                                }
                            }
                            else if (j == 4)
                            {
                                if (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0)
                                {
                                    flag = false;
                                    return Error(ReturnValue += $"第{i + 1}行,第{j + 1}列数据不能为空。");
                                }
                            }
                        }
                    }
                }
                #endregion
                if (flag)
                {
                    //获取物料类型id、单位组
                    List<tmpMaterialTypeDTO> _mtype = new List<tmpMaterialTypeDTO>();
                    List<tmpUnitGroupDTO> _ugrp = new List<tmpUnitGroupDTO>();
                    for (int i = 1; i < CountRow; i++)
                    {
                        var row = sheet.GetRow(i);
                        if (_mtype.Count(x => x.Code.Equals(row.GetCell(3).ToString())) < 1)
                        {
                            tmpMaterialTypeDTO tmp = new tmpMaterialTypeDTO()
                            {
                                Code = row.GetCell(3).ToString()
                            };
                            _mtype.Add(tmp);
                        }
                        if (_ugrp.Count(x => x.Name.Equals(row.GetCell(4).ToString())) < 1)
                        {
                            tmpUnitGroupDTO tmp = new tmpUnitGroupDTO()
                            {
                                Name = row.GetCell(4).ToString(),
                                Units = new List<tmpUnit>()
                                {
                                    new tmpUnit(){Name=row.GetCell(5).ToString() },
                                    new tmpUnit(){Name=row.GetCell(6).ToString() },
                                    new tmpUnit(){Name=row.GetCell(7).ToString() },
                                    new tmpUnit(){Name=row.GetCell(8).ToString() }
                                }
                            };
                            _ugrp.Add(tmp);
                        }
                    }
                    _mtype = _pB_MaterialTypeBus.GetTheDataByCode(_mtype);
                    _ugrp = _pB_MaterialTypeBus.GetTheDataByName(_ugrp);

                    for (int i = 1; i < CountRow; i++)
                    {
                        //实例化实体对象
                        PB_Material_Temp commodity = new PB_Material_Temp();
                        bool bname = false;
                        var row = sheet.GetRow(i);
                        if (row.GetCell(0) != null && row.GetCell(0).ToString().Trim().Length > 0)
                        {
                            commodity.Id = IdHelper.GetId();
                            commodity.CreatorId = _Op.UserId; //"Admin";//_Op.UserId;
                            commodity.CreateTime = DateTime.Now;
                            commodity.Name = row.GetCell(0).ToString();

                        }
                        if (row.GetCell(1) != null && row.GetCell(1).ToString().Trim().Length > 0)
                        {
                            commodity.Code = row.GetCell(1).ToString();
                        }
                        if (row.GetCell(2) != null && row.GetCell(2).ToString().Trim().Length > 0)
                        {
                            commodity.SimpleName = row.GetCell(2).ToString();
                        }
                        if (row.GetCell(3) != null && row.GetCell(3).ToString().Trim().Length > 0)
                        {
                            //commodity.MaterialTypeId = row.GetCell(3).ToString();
                            try
                            {
                                commodity.MaterialTypeId = _mtype.FirstOrDefault(x => x.Code == row.GetCell(3).ToString()).Id;
                            }
                            catch
                            {
                                commodity.MaterialTypeId = "";
                            }
                        }
                        if (row.GetCell(4) != null && row.GetCell(4).ToString().Trim().Length > 0)
                        {
                            try
                            {
                                commodity.UnitGroupId = _ugrp.FirstOrDefault(x => x.Name == row.GetCell(4).ToString()).Id;
                            }
                            catch
                            {
                                commodity.UnitGroupId = "";
                            }
                            //commodity.UnitGroupId = row.GetCell(4).ToString();
                        }
                        var u1 = _ugrp.FirstOrDefault(x => x.Name == row.GetCell(4).ToString()).Units;
                        if (row.GetCell(5) != null && row.GetCell(5).ToString().Trim().Length > 0)
                        {
                            var model = u1.FirstOrDefault(x => x.Name == row.GetCell(5).ToString());
                            if (model != null)
                            {
                                commodity.storageId = model.Id;
                            }
                            else
                            {
                                commodity.storageId = "";
                            }
                            //commodity.storageId = row.GetCell(5).ToString();
                        }
                        if (row.GetCell(6) != null && row.GetCell(6).ToString().Trim().Length > 0)
                        {
                            var model = u1.FirstOrDefault(x => x.Name == row.GetCell(6).ToString());
                            if (model != null)
                            {
                                commodity.saleId = model.Id;
                            }
                            else
                            {
                                commodity.saleId = "";
                            }
                            //commodity.saleId = row.GetCell(6).ToString();
                        }
                        if (row.GetCell(7) != null && row.GetCell(7).ToString().Trim().Length > 0)
                        {
                            var model = u1.FirstOrDefault(x => x.Name == row.GetCell(7).ToString());
                            if (model != null)
                            {
                                commodity.purchaseId = model.Id;
                            }
                            else
                            {
                                commodity.purchaseId = "";
                            }
                        }
                        if (row.GetCell(8) != null && row.GetCell(8).ToString().Trim().Length > 0)
                        {
                            var model = u1.FirstOrDefault(x => x.Name == row.GetCell(8).ToString());
                            if (model != null)
                            {
                                commodity.productionId = model.Id;
                            }
                            else
                            {
                                commodity.productionId = "";
                            }
                        }
                        if (row.GetCell(9) != null && row.GetCell(9).ToString().Trim().Length > 0)
                        {
                            commodity.ProcecureId = row.GetCell(9).ToString();
                        }
                        if (row.GetCell(10) != null && row.GetCell(10).ToString().Trim().Length > 0)
                        {
                            commodity.Spec = row.GetCell(10).ToString();
                        }
                        if (row.GetCell(11) != null && row.GetCell(11).ToString().Trim().Length > 0)
                        {
                            commodity.Max = Convert.ToDouble(row.GetCell(11).ToString());
                        }
                        if (row.GetCell(12) != null && row.GetCell(12).ToString().Trim().Length > 0)
                        {
                            commodity.Min = Convert.ToDouble(row.GetCell(12).ToString());
                        }
                        if (row.GetCell(13) != null && row.GetCell(13).ToString().Trim().Length > 0)
                        {
                            commodity.CusId = row.GetCell(13).ToString();
                        }
                        if (row.GetCell(14) != null && row.GetCell(14).ToString().Trim().Length > 0)
                        {
                            commodity.SupId = row.GetCell(14).ToString();
                        }
                        if (row.GetCell(15) != null && row.GetCell(15).ToString().Trim().Length > 0)
                        {
                            commodity.StorId = row.GetCell(15).ToString();
                        }
                        if (row.GetCell(16) != null && row.GetCell(16).ToString().Trim().Length > 0)
                        {
                            commodity.Price = Convert.ToDouble(row.GetCell(16).ToString());
                        }
                        if (row.GetCell(17) != null && row.GetCell(17).ToString().Trim().Length > 0)
                        {
                            commodity.NewPrice = Convert.ToDouble(row.GetCell(17).ToString());
                        }
                        if (row.GetCell(18) != null && row.GetCell(18).ToString().Trim().Length > 0)
                        {
                            commodity.MinPrice = Convert.ToDouble(row.GetCell(18).ToString());
                        }
                        if (row.GetCell(19) != null && row.GetCell(19).ToString().Trim().Length > 0)
                        {
                            commodity.MaxPrice = Convert.ToDouble(row.GetCell(19).ToString());
                        }
                        if (row.GetCell(20) != null && row.GetCell(20).ToString().Trim().Length > 0)
                        {
                            commodity.SettlePrice = Convert.ToDouble(row.GetCell(20).ToString());
                        }
                        if (row.GetCell(21) != null && row.GetCell(21).ToString().Trim().Length > 0)
                        {
                            commodity.Weight = Convert.ToDouble(row.GetCell(21).ToString());
                        }
                        if (row.GetCell(22) != null && row.GetCell(22).ToString().Trim().Length > 0)
                        {
                            commodity.Area = Convert.ToDouble(row.GetCell(22).ToString());
                        }
                        if (row.GetCell(23) != null && row.GetCell(23).ToString().Trim().Length > 0)
                        {
                            commodity.PackingSpec = row.GetCell(23).ToString();
                        }
                        if (row.GetCell(24) != null && row.GetCell(24).ToString().Trim().Length > 0)
                        {
                            commodity.Length = Convert.ToDouble(row.GetCell(24).ToString());
                        }
                        if (row.GetCell(25) != null && row.GetCell(25).ToString().Trim().Length > 0)
                        {
                            commodity.Width = Convert.ToDouble(row.GetCell(25).ToString());
                        }
                        if (row.GetCell(26) != null && row.GetCell(26).ToString().Trim().Length > 0)
                        {
                            commodity.Height = Convert.ToDouble(row.GetCell(26).ToString());
                        }
                        if (row.GetCell(27) != null && row.GetCell(27).ToString().Trim().Length > 0)
                        {
                            commodity.Estimate = Convert.ToDouble(row.GetCell(27).ToString());
                        }
                        if (row.GetCell(28) != null && row.GetCell(28).ToString().Trim().Length > 0)
                        {
                            commodity.PositionCode = row.GetCell(28).ToString();
                        }
                        if (row.GetCell(29) != null && row.GetCell(29).ToString().Trim().Length > 0)
                        {
                            commodity.Ofmaterial = row.GetCell(29).ToString();
                        }
                        if (row.GetCell(30) != null && row.GetCell(30).ToString().Trim().Length > 0)
                        {
                            if (row.GetCell(30).ToString() == "是")
                            {
                                bname = true;
                            }
                            commodity.IsProduct = bname;
                            bname = false;
                        }
                        if (row.GetCell(31) != null && row.GetCell(31).ToString().Trim().Length > 0)
                        {
                            if (row.GetCell(31).ToString() == "是")
                            {
                                bname = true;
                            }
                            commodity.IsNumber = bname;
                            bname = false;
                        }
                        if (row.GetCell(32) != null && row.GetCell(32).ToString().Trim().Length > 0)
                        {
                            if (row.GetCell(32).ToString() == "是")
                            {
                                bname = true;
                            }
                            commodity.IsMine = bname;
                            bname = false;
                        }
                        if (row.GetCell(33) != null && row.GetCell(33).ToString().Trim().Length > 0)
                        {
                            if (row.GetCell(33).ToString() == "是")
                            {
                                bname = true;
                            }
                            commodity.IsLabour = bname;
                            bname = false;
                        }
                        if (row.GetCell(34) != null && row.GetCell(34).ToString().Trim().Length > 0)
                        {
                            if (row.GetCell(34).ToString() == "是")
                            {
                                bname = true;
                            }
                            commodity.IsQuantity = bname;
                            bname = false;
                        }
                        if (row.GetCell(35) != null && row.GetCell(35).ToString().Trim().Length > 0)
                        {
                            commodity.Remarks = row.GetCell(35).ToString();
                        }
                        if (row.GetCell(36) != null && row.GetCell(36).ToString().Trim().Length > 0)
                        {
                            commodity.ProductCode = row.GetCell(36).ToString();
                        }
                        commodity.CreateTime = DateTime.Now;
                        commodity.IsCruxMaterial = false;
                        commodity.IsKeyprice = false;
                        commodity.IsExtensiveProduction = false;
                        Data.Add(commodity);
                        liststr.Add(commodity.Code + "," + commodity.Name);
                    }

                    ////判断导入的数据是否存在
                    //var lists = _pB_MaterialBus.GetQueryable<PB_Material>().Where(x => liststr.Contains(x.Code + "," + x.Name));
                    //if (lists.Count() > 0)
                    //{
                    //   //物料编号和名称重复过滤 直接执行
                    //    foreach (var remo in lists) {
                    //        var mdata = Data.Find(x=>x.Code==remo.Code&&x.Name==remo.Name);
                    //        if (mdata!=null) {
                    //            Data.Remove(mdata);
                    //        }

                    //    }

                    //    //return Error(ReturnValue = "导入的数据中有已存在数据库中,请不要重复导入");
                    //}
                    ////物料类型
                    //var listMaterialTypeCodes = Data.Select(s => s.MaterialTypeId).Select(s => s.Trim()).Distinct().ToList();
                    //var dicMaterialType = _pB_MaterialBus.GetQueryable<PB_MaterialType>().Where(w => listMaterialTypeCodes.Contains(w.Code)).ToDictionary(k => k.Id, v => v.Code);

                    ////单位组
                    //var listMeasureCodes = Data.Select(s => s.UnitGroupId).Select(s => s.Trim()).Distinct().ToList();
                    //var dicMeasure = _pB_MaterialBus.GetQueryable<Base_UnitGroup>().Where(w => listMeasureCodes.Contains(w.Name)).ToDictionary(k => k.Id, v => v.Name);
                    //if (dicMeasure.Count < listMeasureCodes.Count)
                    //{
                    //    foreach (var item in dicMeasure)
                    //    {
                    //        listMeasureCodes.Remove(item.Value);

                    //    }
                    //    return Error("单位组编号不存在！" + String.Join(",", listMeasureCodes.ToArray()));
                    //}
                    ////客户
                    ////var listCusCodes = Data.Select(s => s.CusId).Distinct().Select(s => s.Trim()).Distinct().ToList();
                    ////var dicCus = _pB_MaterialBus.GetQueryable<PB_Customer>().Where(w => listCusCodes.Contains(w.Name)).ToDictionary(k => k.Id, v => v.Name);

                    ////供应商
                    ////var listSupCodes = Data.Select(s => s.SupId).Distinct().Select(s => s.Trim()).Distinct().ToList();
                    ////var dicSup = _pB_MaterialBus.GetQueryable<PB_Supplier>().Where(w => listSupCodes.Contains(w.Name)).ToDictionary(k => k.Id, v => v.Name);

                    ////仓库
                    ////var listStorCodes = Data.Select(s => s.StorId).Select(s => s.Trim()).Distinct().ToList();
                    ////var dicStor = _pB_MaterialBus.GetQueryable<Base_Department>().Where(w => listStorCodes.Contains(w.Name) && w.Type == 2).ToDictionary(k => k.Id, v => v.Name);

                    ////实例化Redis操作类
                    //_redisOptions.DbChannel = (int)Redis_Type.redis8;
                    //RedisSetHelper redis = new RedisSetHelper(_redisOptions);
                    //List<string> listredis = new List<string>();
                    //if (RedisSetHelper.Exists("BaseUnitGroupRedis"))
                    //{

                    //}
                    //else
                    //{
                    //    _pB_MaterialBus.AddSetRedis();
                    //}
                    //var Base_DepartmentList = _pB_MaterialBus.GetQueryable<Base_Department>().Where(w => w.Type == 2);
                    //string MateriaTypele = "";
                    //foreach (var item in Data)
                    //{
                    //    if (dicMaterialType.ContainsValue(item.MaterialTypeId.Trim()))
                    //        item.MaterialTypeId = dicMaterialType.FirstOrDefault(w => w.Value.Contains(item.MaterialTypeId.Trim())).Key;
                    //    else
                    //          MateriaTypele+= item.MaterialTypeId.Trim()+",";

                    //        //return Error("物料类型编号不存在！");
                    //    //throw new Exception("物料类型编号不存在！");

                    //    if (dicMeasure.ContainsValue(item.UnitGroupId.Trim()))
                    //    {
                    //        //单位组编号
                    //        string groupId = dicMeasure.FirstOrDefault(w => w.Value.Contains(item.UnitGroupId.Trim())).Key;
                    //        item.UnitGroupId = groupId;
                    //        //仓储单位
                    //        if (!item.storageId.IsNullOrEmpty())
                    //        {
                    //            listredis.Clear();
                    //            listredis.Add(""+ groupId +"_"+ item.storageId +"");
                    //            var res = RedisSetHelper.GetHash("BaseUnitGroupRedis", listredis);
                    //            item.storageId = res.FirstOrDefault().Value;
                    //        }
                    //        //销售单位
                    //        if (!item.saleId.IsNullOrEmpty())
                    //        {
                    //            listredis.Clear();
                    //            listredis.Add("" + groupId + "_" + item.storageId + "");
                    //            var res = RedisSetHelper.GetHash("BaseUnitGroupRedis", listredis);
                    //            item.saleId = res.FirstOrDefault().Value;
                    //        }
                    //        //采购单位
                    //        if (!item.purchaseId.IsNullOrEmpty())
                    //        {
                    //            listredis.Clear();
                    //            listredis.Add("" + groupId + "_" + item.storageId + "");
                    //            var res = RedisSetHelper.GetHash("BaseUnitGroupRedis", listredis);
                    //            item.purchaseId = res.FirstOrDefault().Value;
                    //        }
                    //        //生产单位
                    //        if (!item.productionId.IsNullOrEmpty())
                    //        {
                    //            listredis.Clear();
                    //            listredis.Add("" + groupId + "_" + item.storageId + "");
                    //            var res = RedisSetHelper.GetHash("BaseUnitGroupRedis", listredis);
                    //            item.productionId = res.FirstOrDefault().Value;
                    //        }
                    //    }
                    //    else
                    //    {
                    //        return Error("单位组编号不存在！"+ item.UnitGroupId.Trim());
                    //        //throw new Exception("单位组编号不存在！");
                    //    }
                    //    //if (item.CusId == null)
                    //    //{
                    //    //    item.CusId = null;
                    //    //}
                    //    //else if (dicCus.ContainsValue(item.CusId.Trim()))
                    //    //    item.CusId = dicCus.FirstOrDefault(w => w.Value.Contains(item.CusId.Trim())).Key;
                    //    //else
                    //    //    throw new Exception("客户编号不存在！");

                    //    //if (item.SupId == null)
                    //    //{
                    //    //    item.SupId = null;
                    //    //}
                    //    //else if (dicSup.ContainsValue(item.SupId.Trim()))
                    //    //    item.SupId = dicSup.Keys.ToList()[0].ToString();
                    //    //else
                    //    //    throw new Exception("供应商编号不存在！");

                    //    //if (dicStor.ContainsValue(item.StorId.Trim()))
                    //    //    item.StorId = dicStor.FirstOrDefault(w => w.Value.Contains(item.StorId.Trim())).Key;
                    //    //else
                    //    //    throw new Exception("仓库编号不存在！");
                    //    if (!item.StorId.IsNullOrEmpty())
                    //    {
                    //        var dicStor = Base_DepartmentList.Where(w => w.Name == item.StorId).FirstOrDefault();
                    //        item.StorId = dicStor.Id;
                    //    }
                    //}
                    if (Data.Count > 0)
                    {
                        try
                        {
                            _pB_Material_TempBus.AddDataExlAsync(Data, _redisOptions, _mongodbOptions);
                        }
                        catch (Exception ex)
                        {
                            string ErrLogCollection = "ErrLog";
                            MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                            ErrLog err = new ErrLog()
                            {
                                Name = "物料导入",
                                Interface = "/PB/PB_Material_Temp/Import",
                                Type = "错误",
                                Time = DateTime.Now,
                                Remark = ex.Message
                            };
                            mongo.Add<ErrLog>(ErrLogCollection, err);
                        }

                     
                        ReturnValue = $"数据导入成功,共导入{CountRow - 1}条数据。";
                    }
                }
                if (!flag)
                {
                    return Error(ReturnValue = "数据存在问题！" + ReturnValue);
                }
            }
            catch (Exception EX)
            {
                return Error("数据异常！");
            }

            return Success(ReturnValue);

        }


        #endregion
    }
}